LOG_FILE = File.join(File.expand_path(File.dirname(__FILE__)),"../log/win32.log")

begin  

  require "rubygems"
  require "win32/service"
  require 'rbconfig'
  include Config

  require File.join(File.expand_path(File.dirname(__FILE__)),"../lib/robot.rb")

  include Win32

  SERVICE_NAME="win32robot"
  SERVICE_DISPLAYNAME="robot service for win32"
  if ARGV[0]=="install"
    svc=Service.new
    svc.create_service do |s|
      s.service_name=SERVICE_NAME
      s.display_name=SERVICE_DISPLAYNAME

      s.binary_path_name=File.join(CONFIG['bindir'], 'ruby').tr('/', '\\')+" "+File.expand_path($0)
      s.dependencies = []
    end
    svc.close
    puts SERVICE_NAME+" is installed"
  elsif ARGV[0]=='delete'
    if Service.status(SERVICE_NAME).current_state=="running"
      Service.stop(SERVICE_NAME)
    end
    Service.delete(SERVICE_NAME)
    puts SERVICE_NAME+" is deleted"
  else
    if ENV["HOMEDRIVE"]!=nil
      puts <<STRING_END
Options:
    install --  install service for windows
    delete -- delete service
STRING_END
    else
      #it's wrapper class
      class RobotDaemon <Win32::Daemon
        def service_init
          # Give the service time to get everything initialized and running,
          # before we enter the service_main function.
          STDOUT.reopen(File.join(File.expand_path(File.dirname(__FILE__)),"../log/stdout.log"))
          STDERR.reopen(File.join(File.expand_path(File.dirname(__FILE__)),"../log/stderr.log"))
          Robot.init_all()
          #      sleep 10
        end

        def service_main
          while state == RUNNING
            sleep 1
          end
        end
      end
      RobotDaemon.new.mainloop
    end
  end

rescue Exception => err
  File.open(LOG_FILE, 'a+')do |fh| 
    fh.puts 'robot failure: ' + err
    err.backtrace.each(){|e| fh.puts "#{e}"}
  end
  raise
end
